package com.xqboss.apps.controller.system;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xqboss.apps.domain.param.AesParams;
import com.xqboss.apps.dto.consumer.SmsCodeDto;
import com.xqboss.apps.service.aliyun.SampleService;
import com.xqboss.apps.service.consumer.ConsumerInviteRecordService;
import com.xqboss.apps.service.user.UserAssetLidouService;
import com.xqboss.apps.service.user.UserAssetWrenchService;
import com.xqboss.common.annotation.Anonymous;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.AjaxResult;
import com.xqboss.common.core.domain.model.RegisterBody;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.common.utils.aes.AesUtil;
import com.xqboss.common.utils.sms.SmsUtil;
import com.xqboss.framework.web.service.SysRegisterService;
import com.xqboss.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 注册验证
 *
 * @author ruoyi
 */
@Api(tags = {"注册管理"})
@RestController
@RequestMapping("/apps")
public class RegisterController extends BaseController {
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ConsumerInviteRecordService consumerInviteRecordService;
    @Autowired
    private SampleService sampleService;
    @Autowired
    private UserAssetWrenchService userAssetWrenchService;
    @Autowired
    private UserAssetLidouService userAssetLidouService;


    @ApiOperation("星球旅者注册")
    @PostMapping("/register")
    @Log(title = "星球旅者-用户注册", businessType = BusinessType.INSERT)
    public AjaxResult appRegister(@RequestBody AesParams params) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        RegisterBody user = AesUtil.decryptToObject(params.getParamStr(), RegisterBody.class);
        String msg = registerService.appRegister(user);
        if (StringUtils.isEmpty(msg)) {
            //添加邀请记录
            consumerInviteRecordService.addInvite(user);
            // 添加扳手钱包记录
            userAssetWrenchService.addWrenchByUserName(user.getUsername());
            // 添加扳手钱包记录
            userAssetLidouService.addLidouByUserName(user.getUsername());
        }
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    @ApiOperation(value = "星球旅者忘记登录密码")
    @PostMapping(value = "/forgetPassword")
    @Log(title = "星球旅者-忘记登录密码", businessType = BusinessType.UPDATE)
    public AjaxResult forgetPassword(@RequestBody AesParams params) {
        RegisterBody user = AesUtil.decryptToObject(params.getParamStr(), RegisterBody.class);
        String msg = registerService.forgetPassword(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    @ApiOperation("发送手机短信验证码")
    @Anonymous
    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@Validated @RequestBody SmsCodeDto dto, HttpServletRequest request) throws Exception {
        if (ObjUtil.isNull(dto) || StrUtil.isEmpty(dto.getType())) {
            return error("业务类型错误");
        }
        if (!Validator.isMobile(dto.getUsername())) {
            return error("输入的手机号有误");
        }

        //滑动验证
        Boolean check = sampleService.check(dto.getCaptchaVerifyParam(), request);
        if (!check) {
            return error("滑动验证失败");
        }

        String cacheKey = SmsUtil.setCacheKey(dto.getUsername(), dto.getType());
        String code = SmsUtil.getSmsCode(cacheKey);
        if (StrUtil.isNotEmpty(code)) {
            long expire = SmsUtil.getSmsCodeLessExpire(cacheKey);
            if (expire < 60) {
                return error("操作过于频繁，请60秒后再试！");
            }
        }
        code = RandomUtil.randomNumbers(6);
        if (!SmsUtil.sendMsg(dto.getUsername(), code)) {
            return error("发送验证码过于频繁，请稍后再试！");
        }
        SmsUtil.setSmsCode(cacheKey, code);
        return success();
    }
}
